#-*- coding: utf-8 -*-
'''
Created on 2015年6月16日

@author: hzwangzhiwei
'''
from app import apps,login_manager
import flask
from app.utils import RequestUtil, OtherUtil
from flask.globals import request
from app.monitors.RedisMonitor import RedisMonitor
from app.monitors.HttpMonitor import HttpMonitor
import traceback
import os
from werkzeug.utils import secure_filename
from flask_login import UserMixin,login_user,login_required


@apps.route('/', methods=['GET'])
@login_required
def index_page():
    return flask.render_template('index.html',aaa="123e3")

@apps.route('/redis_index', methods=['GET'])
def indexredis_page():
    return flask.render_template('index_page.html')

@apps.route('/redis/<server_md5>.html', methods=['GET'])
def redis_monitor_page(server_md5):
    return flask.render_template('redis_monitor_page.html', server_md5 = server_md5)


@apps.route('/redis_search.json', methods=['GET', 'POST'])
def redis_search():
    try:
        searchkey = RequestUtil.get_parameter(request, 'searchkey', '')
        method = RequestUtil.get_parameter(request, 'method', '')
        searchvalue = RequestUtil.get_parameter(request, 'searchvalue', '')

        host = RequestUtil.get_parameter(request, 'host', '')
        port = int(RequestUtil.get_parameter(request, 'port', '6379'))
        password = RequestUtil.get_parameter(request, 'password', '')
        rst = RedisMonitor().get_key_value(host = host, port = port, password = password,method=method,keyName=searchkey,value=searchvalue)
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        print(str(e))
        rst = {'success': 0, 'data': 'search error'}
    return OtherUtil.object_2_dict(rst)


@apps.route('/redis_ping.json', methods=['GET', 'POST'])
def redis_ping():
    try:
        host = RequestUtil.get_parameter(request, 'host', '')
        port = int(RequestUtil.get_parameter(request, 'port', '6379'))
        password = RequestUtil.get_parameter(request, 'password', '')
        rst = RedisMonitor().ping(host = host, port = port, password = password)
        #rst = {'success': 1, 'data': 'ping error'}
    except:
        rst = {'success': 1, 'data': 'ping error'}
    return OtherUtil.object_2_dict(rst)

@apps.route('/http/<server_md5>.html', methods=['GET'])
def http_monitor_page(server_md5):
    return flask.render_template('http_monitor_page.html', server_md5 = server_md5)

@apps.route('/server_information.json', methods=['GET', 'POST'])
def get_server_paramter():
    try:
        type = RequestUtil.get_parameter(request, 'type', '')
        host = RequestUtil.get_parameter(request, 'host', '1')
        port = int(RequestUtil.get_parameter(request, 'port', '6379'))
        password = RequestUtil.get_parameter(request, 'password', '')
        if type == 'http':
            rst = HttpMonitor().get_info(url = host)
        elif type == 'redis':
            rst = RedisMonitor().get_info(host = host, port = port, password = password)
        else:
            rst = {'success': 1, 'data': 0}
    except Exception as e:
        exstr = traceback.format_exc()
        print(exstr)
        print(str(e))
        rst = {'success': 0, 'data': ''}
    return OtherUtil.object_2_dict(rst)



#定义404页面
@apps.errorhandler(404)
def page_not_found(error):
    return '404'

@apps.errorhandler(502)
def server_502_error(error):
    return '502'

@apps.route('/not_allow', methods=['GET'])
def deny(error):
    return 'You IP address is not in white list...'


UPLOAD_FOLDER = 'app/static/upload'
@apps.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'GET':
       return flask.render_template('largefileupload.html')
    elif request.method == 'POST':
       f = request.files['image_file']
       fname = secure_filename(f.filename)  # 获取一个安全的文件名，且仅仅支持ascii字符；
       print(f.name,f.content_type,f.content_length,f.headers)
       f.save(os.path.join(UPLOAD_FOLDER, fname))
       responsetext = '''
            <p>Your file: {sFileName} has been successfully received.</p>
            <p>Type: {sFileType}</p>
            <p>Size: {sFileSize}</p>
       '''
       print(responsetext.format(sFileName="111",sFileType="100",sFileSize=100))
       # return (responsetext.format(sFileName="111",sFileType="100",sFileSize=100))
       return '{"11":"11"}',200


@apps.route('/download/<filename>')
def download_file(filename):
    UPLOAD_FOLDERS = 'app/static/upload'

    #filename = flask.safe_join(UPLOAD_FOLDER, filename)
    print(flask.safe_join(UPLOAD_FOLDERS,secure_filename(filename)))
    print(os.path.isfile(filename))
    return flask.send_from_directory(UPLOAD_FOLDERS,secure_filename(filename),as_attachment=True)


#当需要验证一个用户的时候
@login_manager.user_loader
def load_user(user_id):
    print("useridddddddd",user_id)
    user = UserMixin()
    return user


@apps.route('/login', methods=['GET', 'POST'])
def login():
    errormsg = ""
    if request.method == 'POST':
        #获取用户的用户名和密码
        username = RequestUtil.get_parameter(request,"username","dl1")
        passwd = RequestUtil.get_parameter(request,"passwd","boco1234")

        print("userid",username)
        #验证用户
        if username == 'dl' and passwd == 'boco1234':
            user = UserMixin()
            user.id = '111111'
            login_user(user)
            flask.flash('Logged in successfully.')
            next = flask.request.args.get('next')
            return flask.redirect(next or flask.url_for('index_page'))
        else:
            errormsg="用户名或密码错误"
    return flask.render_template('login.html',errormsg = errormsg)

@apps.route('/ueditortest')
def ueditortest():
    return flask.render_template('codeeditor.html')

@apps.route('/ueditor/save', methods=['GET', 'POST'])
def ueditorsave():
    plainTxt = RequestUtil.get_parameter(request,"plainTxt","")
    print("onreceivemsg " ,plainTxt)
    with open(os.path.join(UPLOAD_FOLDER,'aa.txt'),'wt') as f:
        f.write(plainTxt)
    return '{"11":"11"}',200
